<?php

namespace Aiweline\AiReviewForMagentoProduct\Controller\Admin;

use Aiweline\AiReviewForMagentoProduct\Helper\Config;
use Aiweline\AiReviewForMagentoProduct\Model\GenratedReviews;
use Weline\Framework\App\Controller\BackendController;
use Weline\Framework\Manager\ObjectManager;

class Reviews extends BackendController
{
    function __construct(
        private GenratedReviews $genratedReviews,
        private Config          $config
    )
    {

    }

    function index()
    {
        $q = $this->request->getQuery('q');
        if ($q) {
            $this->genratedReviews->concat_like('details, title,nickname,product_sku', '%' . $q . '%');
        }
        $reviews = $this->genratedReviews->pagination()->select()->fetch();
        $this->assign('pagination', $reviews->getPagination());
        $this->assign('reviews', $reviews->getItems());
        return $this->fetch();
    }

    function config()
    {
        $configs = $this->config->get('ai_review_for_magento_product_config');
        if ($configs) {
            $configs = json_decode($configs, 1);
        } else {
            $configs = [];
        }
        $default_configs = [
            'store_id' => [
                'label' => 'Your Magento2 Store ID',
                'value' => $this->config->get('store_id')
            ],
            'host' => [
                'label' => 'Your Magento2 Host',
                'value' => $this->config->get('host')
            ],
            'username' => [
                'label' => 'Your Magento2 Admin Username',
                'value' => $this->config->get('username')
            ],
            'password' => [
                'label' => 'Your Magento2 Admin Password',
                'value' => $this->config->get('password')
            ],
            'ai_script' => [
                'label' => 'Ai script Input',
                'value' => $this->config->get('ai_script')
            ],
            'ollama_host' => [
                'label' => 'Ollama Host',
                'value' => $this->config->get('ollama_host')
            ],
            'ollama_model' => [
                'label' => 'Ollama Model',
                'value' => $this->config->get('ollama_model')
            ],
        ];
        if ($configs) {
            foreach ($configs as $key => $item) {
                $default_configs[$key]['value'] = $item;
            }
        }
        $this->assign('configs', $default_configs);
        return $this->fetch();
    }

    public function postSetting()
    {
        $data = $this->request->getPost();
        $this->config->set('ai_review_for_magento_product_config', json_encode($data));
        $this->getMessageManager()->addSuccess('保存成功');
        exec(PHP_BINARY . ' ' . BP . 'bin' . DS . 'w cache:clear -f');
        $this->redirect($this->request->getReferer());
    }
}